package com.ls.fw.data.bean;

import java.util.ArrayList;
import java.util.List;

import com.ls.fw.data.enums.JoinType;
import com.ls.fw.data.visitor.FromVisitor;

public class From implements Cloneable{

	private List<Table> tables = new ArrayList<Table>();
	
	private List<FromItem> fromItems = new ArrayList<FromItem>();
	
	
	/**
	 * 添加一个连接
	 * @author ls
	 * 2014年12月1日下午1:45:37 
	 * @param table1
	 * @param joinType
	 * @param table2
	 * @param table1Field
	 * @param table2Field
	 * @return
	 */
	public From addFromItem(String table1, JoinType joinType, String table2,
			String table1Field, String table2Field){
		this.addFromItem(new FromItem(table1, joinType, table2, table1Field, table2Field));
		return this;
	}
	

	private void add(String schemaName, String name){
		boolean exist = false;
		for (Table t : tables) {
			exist = false;
			if(schemaName!=null){
				if(schemaName.equals(t.getSchemaName()) && name.equals(t.getName())){
					exist = true;
				}
			}else{
				if(name.equals(t.getName())){
					exist = true;
				}else{
					exist = false;
				}
			}
			if(exist){
				break;
			}
		}
		if(!exist){
			this.addTable(schemaName, name);
		}
	}
	
	private void addTable(String schemaName, String name) {
		tables.add(new Table(schemaName, name));
	}
	
	/**
	 * 设置From表
	 * @author ls
	 * 2014年12月1日下午1:59:29 
	 * @param tables  ([schemaName.]name)
	 */
	public From addFromItem(String... tables){
		for (String string : tables) {
			String[] names = string.split(".");
			if(names.length>1){
				this.add(names[0], names[1]);
			}else{
				this.add(null, names[0]);
			}
		}
		return this;
	}
	
	public From addFromItem(String schemaName, String name){
		this.addTable(schemaName, name);
		return this;
	}
	

	public From addFromItem(Table table){
		this.tables.add(table);
		return this;
	}
	

	public From addFromItem(FromItem fromItem){
		String[] names = fromItem.getTable1().split(".");
		if(names.length>1){
			this.add(names[0], names[1]);
		}else{
			this.add(null, names[0]);
		}
		names = fromItem.getTable2().split(".");
		if(names.length>1){
			this.add(names[0], names[1]);
		}else{
			this.add(null, names[0]);
		}
		this.fromItems.add(fromItem);
		return this;
	}
	
	public void accept(FromVisitor visitor) {
		visitor.visit(this);
	}


	public List<FromItem> getFromItems() {
		return fromItems;
	}


	public void setFromItems(List<FromItem> fromItems) {
		this.fromItems = fromItems;
	}


	public List<Table> getTables() {
		return tables;
	}
	
	public Table getTable(){
		return this.getTables().size()>0?this.getTables().get(0):null;
	}
}
